package com.liyghting.datastructurealgorithm.stack;

/**
 * 用栈来实现前进、后退功能
 * 
 * @author LiYiGuang
 * @date 2018/11/21 17:38
 */
public class SimpleBrowser {
	private String currentUrl;
	private StackBasedLinkedList forward;
	private StackBasedLinkedList back;

	SimpleBrowser() {
		forward = new StackBasedLinkedList();
		back = new StackBasedLinkedList();
	}

	public void open(String url) {
		if (currentUrl != null) {
			back.push(url);
			forward.clear();
		}
		show(url, "open");
	}

	public void doForward() {
		if (!canForward()) {
			System.out.println("can not forward");
			return;
		}

		String url = forward.pop();
		back.push(url);
		show(url, "forward");
	}

	public boolean canForward() {
		return forward.size() > 0;
	}

	public boolean canBack() {
		return back.size() > 0;
	}

	public void show(String url, String type) {
		this.currentUrl = url;
		System.out.println(type + " to url = " + url);
	}

	public void doBack() {
		if (!canBack()) {
			System.out.println("can not back");
			return;
		}
		String url = back.pop();
		forward.push(url);
		show(url, "back");
	}

	public void printAll() {
		forward.printAll();
		System.out.println("------------");
		back.printAll();
	}

	public static void main(String[] args) {
		SimpleBrowser simpleBrower = new SimpleBrowser();
		simpleBrower.open("www.baidu.com");
		simpleBrower.open("news.baidu.com");
		simpleBrower.open("news.baidu.com/1");
		simpleBrower.open("news.baidu.com/2");
		simpleBrower.open("news.baidu.com/3");
		simpleBrower.printAll();
		simpleBrower.doBack();
		simpleBrower.doBack();
		simpleBrower.doBack();
		simpleBrower.printAll();
		simpleBrower.doForward();
		simpleBrower.open("www.taobao.com");
		simpleBrower.doForward();
		simpleBrower.printAll();
	}

}
